<!Doctype html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Document</title>
</head>
<body>
<div>分数：<b>0</b></div>
</body>
<script>
var span;
var timer;
createWord()
function createWord(){
    // 随机掉下一个标签，标签中有随机的字符
    span = document.createElement("span");
    // 获取字母a~字母z之间的阿斯克码的随机数
    // 97~122
    var num = getRandom(97,123)
    var word = String.fromCharCode(num)
    // 把随机字符放到span中
    span.innerText = word;
    document.body.appendChild(span)
    // 获取随机的left
    var left = getRandom(0,document.documentElement.clientWidth-30)
    // 给修饰样式
    setStyle(span,{
        width:'30px',
        height:"30px",
        position:"absolute",
        backgroundColor:"red",
        borderRadius:"50%",
        color:"#fff",
        textAlign:"center",
        lineHeight:"30px",
        fontSize:'20px',
        fontWeight:'bold',
        top:0,
        left:left + "px"
    })
    // 往下掉 - 定时器
    timer = setInterval(function(){
        var top = span.offsetTop
        top += 1;
        // 限制top
        if(top>=document.documentElement.clientHeight-30){
            span.parentElement.removeChild(span)
            clearInterval(timer)
            alert('GAME OVER!!!!')
        }
        span.style.top = top + "px"
    },10)
}
// 键盘事件
window.onkeypress = function(e){
    var e = e || window.event;
    var keycode = e.keycode || e.which;
    var w = String.fromCharCode(keycode).toLowerCase()
    if(w === span.innerText){
        // 获取分数
        var score = document.querySelector("b").innerText - 0;
        score++;
        document.querySelector("b").innerText = score
        span.parentElement.removeChild(span)
        clearInterval(timer)
        createWord()
    }
}
// 获取随机数
function getRandom(a,b){
    var max = a;
    var min = b;
    if(a<b){
        max = b;
        min = a
    }
    return parseInt(Math.random()*(max-min))+min
}

// 设置样式
function setStyle(ele,styleObj){
    for(var attr in styleObj){
        ele.style[attr] = styleObj[attr]
    }
}
</script>
</html>